//
//  SearchHistoryViewController.m
//  much
//
//  Created by weijunjie on 2019/1/4.
//  Copyright © 2019年 iOS. All rights reserved.
//

#import "SearchHistoryViewController.h"
#import "StoreSearchViewController.h"
#import "LXReorderableCollectionViewFlowLayout.h"
#import "TextCollectionViewCell.h"
#import "DBHandle.h"
#import "SearchSectionModel.h"
#import "SearchFilterModel.h"

static const CGSize NewSearchHistoryItemCellSize = (CGSize){80, 30};
@interface SearchHistoryViewController() <UITextFieldDelegate,UICollectionViewDataSource, UICollectionViewDelegate>
@property (strong, nonatomic) UICollectionView *contentCollectionView;
@property (nonatomic, strong) UIView *searchView;
@property (nonatomic, strong) UILabel *cancelLabel;
@property (nonatomic, strong) UITextField *searchTextfield;
@property (nonatomic, strong) UIView *removeBGView;
@property (nonatomic, strong) UILabel *removeTitleLabel;
@property (nonatomic, strong) UIButton *removeButton;
/**
 *  存储网络请求的热搜，与本地缓存的历史搜索model数组
 */
@property (nonatomic, strong) NSMutableArray *sectionArray;
/**
 *  存搜索的数组 字典
 */
@property (nonatomic,strong) NSMutableArray *searchArray;
@end


@implementation SearchHistoryViewController

- (void)_reLayout {
    [self setupNavigationItems];
    self.removeButton.hidden = NO;
    self.removeTitleLabel.hidden = NO;;
    [self prepareData];
    [self.contentCollectionView reloadData];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.searchTextfield.text = nil;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.searchTextfield becomeFirstResponder];
    });
}

- (void)setupNavigationItems {
    __weakConfigure
    [self.navigationView addCustomView:self.cancelLabel makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(__weakSelf.navigationView).offset(-15);
        make.height.mas_equalTo(44);
        make.bottom.equalTo(__weakSelf.navigationView);
    } callback:^(UIView *view) {
        
        [__weakSelf disMiss];
    }];
    
    [self.navigationView addCustomView:self.searchView makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(__weakSelf.cancelLabel.mas_left).offset(-10);
        make.left.equalTo(__weakSelf.navigationView).offset(15);
        make.bottom.equalTo(__weakSelf.navigationView).offset(-7);
        make.height.mas_equalTo(30);
    } callback:^(UIView *view) {
    }];
}


/** 准备数据 */
- (void)prepareData {
    /*** 去数据查看 是否有数据*/
    NSDictionary *parmDict = @{@"category":@(self.searchHistoryType)};
    NSDictionary *dbDictionary = [DBHandle statusesWithParams:parmDict];
//    switch (self.searchHistoryType) {
//        case fromArticleType: {
////            [self getArticleSearchHistoryListHTTP];
//            break;
//        }
//        case fromOrderType:
//        case fromStoreType: {
            if (dbDictionary.count) {
                
                SearchSectionModel *model = [SearchSectionModel modelWithDictionary:dbDictionary];
                [self.searchArray addObjectsFromArray:dbDictionary[@"section_content"]];
                [self.sectionArray addObject:model];
            } else {
                SearchSectionModel * model = [[SearchSectionModel alloc] init];
                model.section_id = @"0";
                model.section_title = @"最近搜索";
                [self.sectionArray addObject:model];
            }
//            break;
//        }
//        default:
//            break;
//    }
}

#pragma mark - 懒加载
- (UILabel *)cancelLabel {
    if (!_cancelLabel) {
        _cancelLabel = [[UILabel alloc] init];
        _cancelLabel.text = @"取消";
        _cancelLabel.font = APPFONT(14);
        _cancelLabel.textColor = Color80;
    }
    return _cancelLabel;
}

- (UIView *)searchView {
    if (!_searchView) {
        _searchView = [[UIView alloc] init];
        _searchView.backgroundColor = Color244;
        _searchView.layer.cornerRadius = 15;
        [_searchView addSubview:self.searchTextfield];
        CGFloat totalW = [@"取消" boundingRectWithSize:CGSizeMake(MAXFLOAT, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : APPFONT(14)} context:nil].size.width;
        totalW = ScreenWidth - totalW - 54;
        [_searchTextfield mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.searchView).offset(14);
            make.top.bottom.right.equalTo(self.searchView);
            make.width.mas_equalTo(totalW);
            make.height.mas_equalTo(30);
        }];
    }
    return _searchView;
}

- (UITextField *)searchTextfield {
    if (!_searchTextfield) {
        _searchTextfield = [[UITextField alloc] init];
        _searchTextfield.textAlignment = NSTextAlignmentLeft;
        _searchTextfield.textColor = Color34;
        _searchTextfield.font = ICONFONT(14);
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.searchTextfield becomeFirstResponder];
        });
        _searchTextfield.placeholder = @"\uE6a4 搜索商品，低价好物任你选";
        _searchTextfield.filterActionType = FilterEmojiType;
        [_searchTextfield setValue:Color140 forKeyPath:@"_placeholderLabel.textColor"];
        _searchTextfield.clearButtonMode = UITextFieldViewModeWhileEditing;
        _searchTextfield.delegate = self;
    }
    return _searchTextfield;
}

- (UIView *)removeBGView {
    if (!_removeBGView) {
        _removeBGView = [UIView new];
        [self.view addSubview:_removeBGView];
        [_removeBGView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.navigationView.mas_bottom).with.offset(12);
            make.left.and.right.equalTo(self.view);
            make.height.mas_equalTo(20);
        }];
    }
    return _removeBGView;
}

- (UILabel *)removeTitleLabel {
    if (!_removeTitleLabel) {
        _removeTitleLabel = [UILabel new];
        _removeTitleLabel.textColor = Color140;
        _removeTitleLabel.font = APPFONT(14);
        _removeTitleLabel.textAlignment = NSTextAlignmentLeft;
        _removeTitleLabel.text = @"最近搜索";
        [self.removeBGView addSubview:_removeTitleLabel];
        [_removeTitleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.removeBGView).with.offset(15);
            make.right.equalTo(self.removeBGView.mas_centerX);
            make.centerY.equalTo(self.removeBGView);
        }];
    }
    return _removeTitleLabel;
}

- (UIButton *)removeButton {
    if (!_removeButton) {
        _removeButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_removeButton setTitle:N_DELETE forState:UIControlStateNormal];
        _removeButton.titleLabel.font = ICONFONT(15);
        [_removeButton setTitleColor:Color140 forState:UIControlStateNormal];
        [_removeButton addTarget:self action:@selector(progressRemoveButton) forControlEvents:UIControlEventTouchUpInside];
        [self.removeBGView addSubview:_removeButton];
        [_removeButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(self.removeBGView).with.offset(- 8);
            make.bottom.and.top.equalTo(self.removeBGView);
            make.width.mas_equalTo(50);
        }];
    }
    return _removeButton;
}

- (UICollectionView *)contentCollectionView {
    if (!_contentCollectionView) {
        LXReorderableCollectionViewFlowLayout *collectionViewFlowLayout = [[LXReorderableCollectionViewFlowLayout alloc] init];
        collectionViewFlowLayout.itemSize = NewSearchHistoryItemCellSize;
        collectionViewFlowLayout.minimumLineSpacing = 10;
        collectionViewFlowLayout.minimumInteritemSpacing = 8;
        collectionViewFlowLayout.sectionInset = UIEdgeInsetsMake(10, 15, 10, 15);
        _contentCollectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:collectionViewFlowLayout];
        _contentCollectionView.collectionViewLayout = collectionViewFlowLayout;
        _contentCollectionView.delegate = self;
        _contentCollectionView.dataSource = self;
        [_contentCollectionView registerNib:[UINib nibWithNibName:TextCollectionViewCellClassName bundle:nil] forCellWithReuseIdentifier:TextCollectionViewCellClassName];
        _contentCollectionView.backgroundColor = [UIColor whiteColor];
        _contentCollectionView.scrollEnabled = NO;
        [self.view addSubview:_contentCollectionView];
        
        [_contentCollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.removeBGView.mas_bottom);
            make.left.and.right.and.bottom.equalTo(self.view);
        }];
    }
    return _contentCollectionView;
}

- (NSMutableArray *)searchArray {
    if (_searchArray == nil) {
        _searchArray = [NSMutableArray array];
    }
    return _searchArray;
}

- (NSMutableArray *)sectionArray {
    if (_sectionArray == nil) {
        _sectionArray = [NSMutableArray array];
    }
    return _sectionArray;
}


- (void)disMiss {
    [self.navigationController popViewControllerAnimated:NO];
}

- (void)progressRemoveButton {
    if (self.sectionArray.count > 0) {
//        switch (self.fromArticleOrStoreType) {
//            case fromArticleType: {
//                [self deleteArticleSearchHistoryHTTP];
//                break;
//            }
//            case fromOrderType:
//            case fromStoreType: {
                [self releaseSearchArray];
//                break;
//            }
//            default:
//                break;
        }
//    }
}

- (void)releaseSearchArray {
    [self.searchArray removeAllObjects];
//    [self.articleHistoryArray removeAllObjects];
    [self reloadData:nil];
}

#pragma mark - UISearchBarDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [self pushWithContentText:textField.text];
    return YES;
}

- (void)pushWithContentText:(NSString *)contentText {
    if (self.beRequest) {
        return;
    }
    self.beRequest = YES;
    [self.searchTextfield resignFirstResponder];
    [SVProgressHUD showWithStatus:@"加载中..."];
    SearchFilterModel *filterModel = [[SearchFilterModel alloc] init];
    filterModel.keyWord = contentText;
    filterModel.pageIndex = 0;
    [MuchStoreRequestManager storeSearchWithFilterModel:filterModel successBlock:^(id  _Nonnull responseObject, NSInteger totalPages) {
        self.beRequest = NO;
        StoreSearchViewController *vc = [[StoreSearchViewController alloc] init];
        [SVProgressHUD dismiss];
        vc.filterModel = filterModel;
        vc.data = responseObject;
        [self.navigationController pushViewController:vc animated:YES];
    } failureBlock:^(NSString *error) {
        
        self.beRequest = NO;
        [SVProgressHUD showErrorWithStatus:error];
    }];
    
    NSString *text = contentText;
    if ([[text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] isEqualToString:@""]){
        return;
    }
    
    if (![self.searchArray containsObject:[NSDictionary dictionaryWithObject:text forKey:@"content_name"]]) {
        [self reloadData:text];
    }
    
}

- (void)reloadData:(NSString *)textString {
    if (textString.hasValue) {
        [self.searchArray insertObject:[NSDictionary dictionaryWithObject:textString forKey:@"content_name"] atIndex:0];
    }
    
    NSDictionary *searchDict = @{@"section_id":@(self.searchHistoryType), @"section_title":@"最近搜索", @"section_content":self.searchArray};
    
    /** 由于数据量并不大 这样每次存入再删除没问题 存数据库 */
    NSDictionary *parmDict = @{@"category":@(self.searchHistoryType)};
    [DBHandle saveStatuses:searchDict andParam:parmDict];
    
    SearchSectionModel *model = [SearchSectionModel modelWithDictionary:searchDict];
    if (self.sectionArray.count > 0) {
        [self.sectionArray removeLastObject];
    }
    
    [self.sectionArray insertObject:model atIndex:0];
    [self.contentCollectionView reloadData];
}


#pragma mark UICollectionViewDataSource,UICollectionViewDelegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.searchArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    TextCollectionViewCell *cell = (TextCollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:TextCollectionViewCellClassName forIndexPath:indexPath];
    cell.textFont = APPFONT(12);
    cell.cornerRadius = 15;
    cell.backgroundColor = Color244;
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath {
    TextCollectionViewCell *textCollectionViewCell = (TextCollectionViewCell *)cell;
    SearchSectionModel *sectionModel = self.sectionArray[indexPath.section];
    SearchModel *contentModel = sectionModel.section_content[indexPath.row];
    if (contentModel.content_name.hasValue) {
        textCollectionViewCell.textValue = contentModel.content_name;
    } else {
        textCollectionViewCell.textValue = contentModel.order_content_name;
    }
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    // 自适应宽
    SearchSectionModel *sectionModel = self.sectionArray[indexPath.section];
    SearchModel *contentModel = sectionModel.section_content[indexPath.row];
    NSString *endString;
    if (contentModel.content_name.hasValue) {
        endString = contentModel.content_name;
    } else {
        endString = contentModel.order_content_name;
    }
    CGFloat w = [endString boundingRectWithSize:CGSizeMake(MAXFLOAT, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:APPFONT(12)} context:nil].size.width;
    CGSize endSize = CGSizeMake(w +30, 30.0f);
    
    return endSize;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    SearchSectionModel *sectionModel = self.sectionArray[indexPath.section];
    SearchModel *contentModel = sectionModel.section_content[indexPath.row];
    NSString *text = contentModel.content_name;
    [self pushWithContentText:text];
}

@end
